<template>
  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="车辆编号">
      <el-input v-model="searchForm.vehicleId" placeholder="车辆编号" clearable />
    </el-form-item>
    <el-form-item label="车牌号">
      <el-input v-model="searchForm.licensePlate" placeholder="车牌号" clearable />
    </el-form-item>
    <el-form-item label="车辆状态">
      <el-select v-model="searchForm.status" placeholder="车辆状态" clearable>
        <el-option v-for="status in VehicleStatus" :key="status.code" :label="status.label" :value="status.code"/>
      </el-select>
    </el-form-item>
    <el-form-item label="驾驶员">
      <el-input v-model="searchForm.name" placeholder="请输入完整姓名" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="pageSelectList">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click=VehicleAdd>新增</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" :border="parentBorder" style="width: 100%">
    <el-table-column type="expand">
      <template #default="props">
        <div m="4">
          <p m="t-0 b-2">行程编号: {{ props.row.tripNumber }}</p>
          <p m="t-0 b-2">车型: {{ props.row.type }}</p>
          <p m="t-0 b-2">车辆座位数: {{ props.row.seatingCapacity }}</p>
          <p m="t-0 b-2">创建时间: {{ props.row.founderDate }}</p>
          <p m="t-0 b-2">修改时间: {{ props.row.modifierDate }}</p>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="车辆编号" prop="vehicleId" width=120px />
    <el-table-column label="车牌号" prop="licensePlate" width=120px />
    <el-table-column label="车辆状态" prop="status" width="120px">
      <template #default="scope">
        <!-- <span>{{ getStatusLabel(scope.row.status) }}</span> -->
        <span :style="{ color: getStatusLabel(scope.row.status).color }">
          {{ getStatusLabel(scope.row.status).label }}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="车辆驾驶员" prop="name" width=140px />
    <el-table-column label="起始地" prop="start" width=140px />
    <el-table-column label="目的地" prop="end" width=140px />
    <el-table-column label="购买日期" prop="buyDate" />
    <el-table-column label="保养日期" prop="maintenanceDate" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" type="warning" @click="ListById(scope.row.id)">修改</el-button>
        <el-button size="small" type="danger" @click="openDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[5, 10, 15, 25]"
      :size="size" :disabled="disabled" :background="background" layout="->, total, sizes, prev, pager, next"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <div>
    <el-drawer v-model="dialog" title="修改车辆信息" direction="rtl" class="demo-drawer">
      <div class="demo-drawer__content">
        <el-form :model="form">
          <el-form-item label="车辆编号" :label-width="formLabelWidth">
            <el-input v-model="form.vehicleId" autocomplete="off" />
          </el-form-item>
          <el-form-item label="车牌号" :label-width="formLabelWidth">
            <el-input v-model="form.licensePlate" autocomplete="off" />
          </el-form-item>
          <el-form-item label="车辆状态" :label-width="formLabelWidth">
            <el-select v-model="form.status" placeholder="车辆状态" clearable>
              <el-option v-for="status in VehicleStatus" :key="status.code" :label="status.label"
                :value="status.code" />
            </el-select>
          </el-form-item>
          <el-form-item label="驾驶员" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="驾驶路线" :label-width="formLabelWidth">
            <el-select v-model="form.tripNumber" placeholder="请选择驾驶路线">
              <el-option v-for="route in routes" :key="route.id" :label="route.tripNumber" :value="route.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="车辆型号" :label-width="formLabelWidth">
            <el-select v-model="form.type" placeholder="请选择车辆型号">
              <el-option v-for="typeItem in VehicleType" :key="typeItem.id" :label="typeItem.type"
                :value="typeItem.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="购买日期" :label-width="formLabelWidth">
            <el-date-picker v-model="form.buyDate" placeholder="选择日期" />
          </el-form-item>
          <el-form-item label="保养日期" :label-width="formLabelWidth">
            <el-date-picker v-model="form.maintenanceDate" placeholder="选择日期"
              />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中 ...' : '提交' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>


<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import type { ComponentSize } from 'element-plus'
import { useRouter } from 'vue-router';
import { ElDrawer, ElMessage, ElMessageBox } from 'element-plus'
import { getListById, travelRoute, TypeList, getPageList, updateList, deleteList } from '../api/service.js'
import { VehicleStatus } from '../utils/status.js';
const router = useRouter();

const formLabelWidth = '160px'

const dialog = ref(false)
const loading = ref(false)

const form = reactive({
  vehicleId: '',
  licensePlate: '',
  status: '',
  name: '',
  tripNumber: '',
  buyDate: '',
  // founderDate: '',
  maintenanceDate: '',
  type: ''
})

const onClick = async () => {
  try {
    const result = await updateList(form);
    console.log(form)
    if (result.data.code === 200) {
      ElMessage.success(result.data.msg ? result.data.msg : '修改成功');
      loading.value = true
      setTimeout(() => {
        loading.value = false
        dialog.value = false
      }, 400);
      pageSelectList();
    }else{
      ElMessage.error(result.data.msg? result.data.msg: '无法修改')
    }
  } catch (error) {
    ElMessage.error("请正常点击路线和行程来确认信息")
  }
  dialog.value = false
}


const cancelForm = () => {
  loading.value = false
  dialog.value = false
  form.vehicleId = '',
    form.licensePlate = '',
    form.status = '',
    form.name = '',
    form.tripNumber = '',
    form.buyDate = '',
    form.maintenanceDate = '',
    form.type = ''
}

const VehicleAdd = () => {
  router.push('/vehicle/add')
}

const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(0)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  pageSize4.value = val;
  pageSelectList();
};

const handleCurrentChange = (val: number) => {
  currentPage4.value = val;
  pageSelectList();
};

const searchForm = reactive({
  vehicleId: '',
  licensePlate: '',
  status: '',
  name: ''
})

const parentBorder = ref(false)
const tableData = ref([])

const ListById = async (id: number) => {
  dialog.value = true
  console.log(id);
  ElMessage.warning('必须进行路线和汽车类型的点击');
  try {
    const result = await getListById(id);
    if (result.data.code === 200) {
      const data = result.data.data[0];
      Object.assign(form, data)
    }
  } catch (error) {
    ElMessage.error('出现错误')
  }
}



const routes = ref([])
const VehicleType = ref([])

const getRoutes = async () => {
  try {
    const result = await travelRoute();
    if (result.data.code === 200) {
      routes.value = result.data.data
    }
  } catch (error) {
    ElMessage.error("路线错误")
  }
}

const getType = async () => {
  try {
    const result = await TypeList();
    if (result.data.code === 200) {
      VehicleType.value = result.data.data;
    }
  } catch (error) {
    ElMessage.error("类型错误")
  }
}

const pageSelectList = async () => {
  const payload = {
    page: currentPage4.value,
    pageSize: pageSize4.value,
    vehicleId: searchForm.vehicleId,
    licensePlate: searchForm.licensePlate,
    status: searchForm.status,
    name: searchForm.name
  };
  console.log(payload)
  try {
    const result = await getPageList(payload)
    console.log(result.data.code)
    if (result.data.code === 200) {
      total.value = result.data.data.total;
      tableData.value = result.data.data.recodes;
      ElMessage.success('车辆列表')
    } else {
      ElMessage.error(result.data.msg ? result.data.msg : '未查询到任何信息');
    }
  } catch (error) {
    ElMessage.error('查询出错');
  }
};

const openDelete = (id: number) => {
  ElMessageBox.confirm(
    '确定删除该车辆信息?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await deleteList(id);
      if (result.data.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }
      pageSelectList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const statusColorMap = {
  1: '#4caf50',  // Example status color
  0: '#ff9800',  // Example status color
  2: '#f44336',  // Example status color
  // Add more status colors here
}

const getStatusLabel = (status: number) => {
  const statusItem = VehicleStatus.value.find(item => item.code === status)
  if(status === -1){
    status = 2;
  }
  const color = statusColorMap[status] || '#000'  // Default to black if status not found
  return { label: statusItem ? statusItem.label : '未知', color }
}

onMounted(() => {
  // getVehicleList(),
  pageSelectList(),
    getRoutes(),
    getType()
})

</script>


<style scoped>
.demo-form-inline .el-input {
  width: 200px;
}

.demo-form-inline .el-select {
  width: 200px;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.type-status-class {
  color: #fff;
  padding: 3px 8px;
  border-radius: 10px;
  display: inline-block;
  width: 60px;
  text-align: center;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>